package so.shanku.essential.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.*;
import android.widget.*;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.ArticalSearchActivity;
import so.shanku.essential.adapter.MenuAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.view.NoTouchLinearLayout;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Jaelyn on 2015/9/6 0006.
 * 页面需要获取屏幕的宽高 发现
 */
public class FindFragment extends BaseFragment {

    /**
     * top view init
     */
    @ViewInject(R.id.main_top_layout) //title
    private LinearLayout main_top_layout;
    @ViewInject(R.id.title_menu_iv)
    private ImageView title_menu_iv;

    @ViewInject(R.id.item_left_layout) //title
    private LinearLayout item_left_layout;
    @ViewInject(R.id.item_right_layout) //title
    private RelativeLayout item_right_layout;
    @ViewInject(R.id.item_left_tv)
    private TextView item_left_tv;
    @ViewInject(R.id.item_right_tv)
    private TextView item_right_tv;

    @ViewInject(R.id.iv_search)
    private ImageView iv_search;

    /**
     * drop down menu container
     */
    @ViewInject(R.id.no_touch_layout)
    private NoTouchLinearLayout no_touch_layout;

    /**
     * 当前选中项的ID
     */
    private String leftId = "0";
    private String rightId = "0";

    /**
     * 保存点击过得fragment
     */
    private HashMap<Integer, BaseFragment> fragments = new HashMap();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.find_fragment_layout, container, false);
        ViewUtils.inject(this, view);
        item_left_tv.setText(R.string.source);
        item_right_tv.setText(R.string.special_subject);

        title_menu_iv.setVisibility(View.INVISIBLE);
        loadingToast.show();
        getServerData(0);
        showLeftFragment();
        return view;
    }

    /**
     * 获取服务器端数据
     *
     * @param requestType 请求类型
     */
    public void getServerData(int requestType) {
        HashMap<String, Object> params = new HashMap<String, Object>();

        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetFindTopCategoryData);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetFindTopCategoryData);
        getDataUtil.getData(queue);
    }


    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(activity, entity.getInfo())) {
                    JsonMap data = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                    leftData = (ArrayList<JsonMap<String, Object>>) data.getList_JsonMap("articalCategories");
                    rightData = (ArrayList<JsonMap<String, Object>>) data.getList_JsonMap("specialSubjectCategories");
                }
            } else {
                ShowGetDataError.showNetError(activity);
            }
            loadingToast.dismiss();
        }

    };

    /*
     * 购物车
     * @param view
     */
    @OnClick(R.id.title_menu_iv)
    public void title_menu_iv_click(View view) {
//        if (currentFragment == fragments.get(0)) {
//            activity.jumpTo(ArticalSearchActivity.class);
//        }else {
        activity.jumpToShopCart();
        //}
    }


    private ArrayList<JsonMap<String, Object>> leftData;

    /**
     * 来源
     *
     * @param view
     */
    @OnClick(R.id.item_left_layout)
    public void item_left_layout_click(View view) {
        if (currentFragment == fragments.get(0)) {
            if (no_touch_layout.getVisibility() == View.VISIBLE) {
                setSelectLeftRightStatus(1, 0);
            } else {
                setSelectLeftRightStatus(2, 0);
                ListView listView = new ListView(activity);
                listView.setDivider(activity.getResources().getDrawable(R.drawable.hor_line));
                int pad = getResources().getDimensionPixelSize(R.dimen.common_margin);
                listView.setPadding(pad, 0, pad, 0);
                listView.setBackgroundResource(R.drawable.cus_grey_round_border_frame);
                MenuAdapter menuAdapter = new MenuAdapter(activity, leftData);
                listView.setAdapter(menuAdapter);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MyApplication.getInstance().getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
                no_touch_layout.addView(listView, params);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        item_left_tv.setText(leftData.get(position).getStringNoNull("categoryName"));
                        leftId = leftData.get(position).getString("categoryId");
                        fragments.remove(0);
                        showLeftFragment();
                    }
                });
            }
        } else {
            showLeftFragment();
        }
    }

    private void showLeftFragment() {
        title_menu_iv.setVisibility(View.INVISIBLE);
        setSelectLeftRightStatus(1, 0);
        if (fragments.get(0) != null) {
            replaceView(fragments.get(0));
        } else {
            ArticalFragment articalFragment = new ArticalFragment();
            bundle.putString(Constant.ID, leftId);
            articalFragment.setArguments(bundle);
            replaceView(articalFragment);
            fragments.put(0, articalFragment);
        }
    }

    /**
     * 设置左侧按钮状态 0:不选中,1:选中,2:下拉弹框,
     *
     * @param i
     */
    private void setSelectLeftRightStatus(int i, int j) {
        Drawable popStateDrawable1 = getResources().getDrawable(R.drawable.pop_none);
        Drawable popStateDrawable2 = getResources().getDrawable(R.drawable.pop_down_grey);
        Drawable popStateDrawable3 = getResources().getDrawable(R.drawable.pop_down_white);

        Drawable bottomStateDrawable1 = getResources().getDrawable(R.drawable.hor_line_trans_2);
        Drawable bottomStateDrawable2 = getResources().getDrawable(R.drawable.hor_line_white_2);

        // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
        popStateDrawable2.setBounds(0, 0, popStateDrawable2.getMinimumWidth(), popStateDrawable2.getMinimumHeight());
        popStateDrawable3.setBounds(0, 0, popStateDrawable3.getMinimumWidth(), popStateDrawable3.getMinimumHeight());

        bottomStateDrawable1.setBounds(0, 0, bottomStateDrawable1.getMinimumWidth(), bottomStateDrawable1.getMinimumHeight());
        bottomStateDrawable2.setBounds(0, 0, bottomStateDrawable2.getMinimumWidth(), bottomStateDrawable2.getMinimumHeight());

        switch (i) {
            case 0:
                item_left_tv.setCompoundDrawables(null, null, popStateDrawable1, null);
                item_left_layout.setBackgroundResource(R.drawable.nav_bar);
                break;
            case 1:
                item_left_layout.setBackgroundResource(R.drawable.nav_bar);
                item_left_tv.setCompoundDrawables(null, null, popStateDrawable2, bottomStateDrawable2);
                break;
            case 2:
                item_left_layout.setBackgroundResource(R.drawable.nav_bar_selected);
                item_left_tv.setCompoundDrawables(null, null, popStateDrawable3, bottomStateDrawable1);
                break;
            default:
        }
        switch (j) {
            case 0:
                item_right_layout.setBackgroundResource(R.drawable.nav_bar);
                item_right_tv.setCompoundDrawables(null, null, popStateDrawable1, null);
                break;
            case 1:
                item_right_layout.setBackgroundResource(R.drawable.nav_bar);
                item_right_tv.setCompoundDrawables(null, null, popStateDrawable2, bottomStateDrawable2);
                break;
            case 2:
                item_right_layout.setBackgroundResource(R.drawable.nav_bar_selected);
                item_right_tv.setCompoundDrawables(null, null, popStateDrawable3, bottomStateDrawable1);
                break;
            default:
        }

        if (i == 2 || j == 2) {
            no_touch_layout.setVisibility(View.VISIBLE);
        } else {
            no_touch_layout.setVisibility(View.GONE);
            no_touch_layout.removeAllViews();
        }
    }


    private ArrayList<JsonMap<String, Object>> rightData;

    /**
     * 排序
     *
     * @param view
     */
    @OnClick(R.id.item_right_layout)
    public void item_right_layout_click(View view) {
        if (currentFragment == fragments.get(1)) {
            if (no_touch_layout.getVisibility() == View.VISIBLE) {
                setSelectLeftRightStatus(0, 1);
            } else {
                setSelectLeftRightStatus(0, 2);
                View view1 = new View(activity);
                ListView listView = new ListView(activity);
                listView.setDivider(activity.getResources().getDrawable(R.drawable.hor_line));
                int pad = getResources().getDimensionPixelSize(R.dimen.common_margin);
                listView.setPadding(pad, 0, pad, 0);
                listView.setBackgroundResource(R.drawable.cus_grey_round_border_frame);
                MenuAdapter menuAdapter = new MenuAdapter(activity, rightData);
                listView.setAdapter(menuAdapter);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MyApplication.getInstance().getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
                no_touch_layout.addView(view1, params);
                no_touch_layout.addView(listView, params);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        item_right_tv.setText(rightData.get(position).getStringNoNull("categoryName"));
                        rightId = rightData.get(position).getStringNoNull("categoryId");
                        fragments.remove(1);
                        showRightFragment();
                    }
                });
            }
        } else {
            showRightFragment();
            setSelectLeftRightStatus(0, 1);
        }
    }

    /**
     * fragments 传值
     */
    private Bundle bundle = new Bundle();

    private void showRightFragment() {
        title_menu_iv.setVisibility(View.VISIBLE);

        setSelectLeftRightStatus(0, 1);
        if (fragments.get(1) != null) {
            replaceView(fragments.get(1));
        } else {
            SpecialSubjectFragment articalFragment = new SpecialSubjectFragment();
            bundle.putString(Constant.ID, rightId);
            articalFragment.setArguments(bundle);
            replaceView(articalFragment);
            fragments.put(1, articalFragment);
        }
    }


    private Fragment currentFragment;

    private void replaceView(BaseFragment fragment) {

        FragmentTransaction transaction = this.getFragmentManager().beginTransaction();
//			FragmentTransaction transaction = mFragmentMan.beginTransaction().setCustomAnimations(
//					android.R.anim.fade_in, R.anim.slide_out);
        if (currentFragment != null) {
            if (!fragment.isAdded()) {    // 先判断是否被add过
                transaction.hide(currentFragment).add(R.id.find_content_layout, fragment).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(currentFragment).show(fragment).commit(); // 隐藏当前的fragment，显示下一个
            }
        } else {
            transaction.add(R.id.find_content_layout, fragment).commit(); // add下一个到Activity中
        }
        currentFragment = fragment;
    }


    /**
     * 搜索图标
     *
     * @param view
     */
    @OnClick(R.id.iv_search)
    public void iv_search_click(View view) {
        Intent findSearchIntent = new Intent(activity, ArticalSearchActivity.class);
        activity.jumpTo(findSearchIntent, false);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        backKeyClick();
    }

    /**
     * back 键处理
     *
     * @return true：消费此次返回  false  不处理
     */
    public boolean backKeyClick() {
        no_touch_layout.setVisibility(View.GONE);
        if (currentFragment == fragments.get(1)) {
            setSelectLeftRightStatus(0, 1);
            return true;
        }

        if (currentFragment == fragments.get(0)) {
            setSelectLeftRightStatus(1, 0);
            return true;
        }
        return false;
    }
}